package org.jsola.hr.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jsola.common.DateKit8;
import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.EmpInfoFieldToString;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.common.ExcelKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.constant.SocPayCostType;
import org.jsola.hr.dao.ISocCheckItemDAO;
import org.jsola.hr.dto.SocCheckItemAddDTO;
import org.jsola.hr.dto.SocCheckItemUpdateDTO;
import org.jsola.hr.entity.SocCheckItemDO;
import org.jsola.hr.entity.SocProgDO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.query.EmpInfoExportColumn;
import org.jsola.hr.query.EmpInfoExportQuery;
import org.jsola.hr.query.EmpInfoQuery;
import org.jsola.hr.query.SocCheckItemQuery;
import org.jsola.hr.service.ISocCheckItemService;
import org.jsola.hr.service.ISocCheckService;
import org.jsola.hr.service.ISocProgService;
import org.jsola.hr.vo.EmpInfoListVO;
import org.jsola.hr.vo.SocCheckItemListVO;
import org.jsola.hr.vo.SocCheckItemVO;
import org.jsola.hr.vo.SocCheckVO;
import org.jsola.hr.vo.excel.SocCheckItemExportVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 校验子项表
 *
 * @author zhr
 */
@Service("hrSocCheckItemServiceImpl")
public class SocCheckItemServiceImpl implements ISocCheckItemService {

    @Autowired
    private ISocCheckItemDAO socCheckItemDAO;

    @Autowired
    private ISocProgService socProgService;

    @Autowired
    private ISocCheckService socCheckService;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public SocCheckItemVO save(SocCheckItemAddDTO socCheckItemAddDTO, TokenUser tokenUser) {
        // 转DO
        SocCheckItemDO socCheckItemDO = socCheckItemAddDTO.to(SocCheckItemDO.class);
        // 保存
        socCheckItemDO = save(socCheckItemDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return socCheckItemDO.to(SocCheckItemVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(SocCheckItemUpdateDTO socCheckItemUpdateDTO, TokenUser tokenUser) {
        //转DO
        SocCheckItemDO socCheckItemDO = socCheckItemUpdateDTO.to(SocCheckItemDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(socCheckItemDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... socCheckItemIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) socCheckItemIds);
    }


    @Override
    public SocCheckItemVO selectById(String socCheckItemId, String siteId) {
        SocCheckItemDO socCheckItemDO = selectDOById(socCheckItemId, siteId);
        if (socCheckItemDO == null) {
            return null;
        }
        return socCheckItemDO.to(SocCheckItemVO.class);
    }

    @Override
    public List<SocCheckItemListVO> select(SocCheckItemQuery socCheckItemQuery, String siteId) {
        List<SocCheckItemDO> socCheckItemDOList = selectDO(socCheckItemQuery, siteId);
        if (CollectionUtils.isEmpty(socCheckItemDOList)) {
            return socCheckItemDOList == null ? null : new ArrayList<>();
        }
        return socCheckItemDOList.stream()
                .map(socCheckItemDO -> socCheckItemDO.to(SocCheckItemListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(SocCheckItemQuery socCheckItemQuery, String siteId) {
        Example example = buildExample(socCheckItemQuery, siteId);
        return socCheckItemDAO.selectCountByExample(example);
    }

    @Override
    public Page<SocCheckItemListVO> selectPage(SocCheckItemQuery socCheckItemQuery, String siteId) {
        Example example = buildExample(socCheckItemQuery, siteId);
        Page<SocCheckItemDO> page = socCheckItemDAO.selectPageByExample(example,
                socCheckItemQuery.getPageNo(),
                socCheckItemQuery.getPageSize());

        return page.to(SocCheckItemListVO.class);
    }

    @Override
    public SocCheckItemDO selectDOById(String socCheckItemId, String siteId) {
        return listById(socCheckItemId, siteId);
    }

    @Override
    public List<SocCheckItemDO> selectDO(SocCheckItemQuery socCheckItemQuery, String siteId) {
        Example example = buildExample(socCheckItemQuery, siteId);
        return socCheckItemDAO.selectByExample(example);
    }


    @Override
    public List<SocCheckItemExportVO> selectExportList(SocCheckItemQuery socCheckItemQuery, TokenUser tokenUser) {
        List<SocCheckItemExportVO> result = new ArrayList<>();
        List<SocCheckItemVO> socCheckItemList = additionalSocCheckItem(socCheckItemQuery.getSocCheckId(),
                socCheckItemQuery.getWrongsStatus(), tokenUser);
        for (SocCheckItemVO socCheckItemVO : socCheckItemList) {
            SocCheckItemExportVO resultItem = socCheckItemVO.to(SocCheckItemExportVO.class);
            // 个人社保
            resultItem.setPersonSocStr(resultItem.getSysPersonalSocAmount().stripTrailingZeros().toPlainString() + "/" +
                    resultItem.getExcelPersonalSocAmount().stripTrailingZeros().toPlainString());
            // 个人公积金
            resultItem.setPersonPfStr(resultItem.getSysPersonalPfAmount().stripTrailingZeros().toPlainString() + "/" +
                    resultItem.getExcelPersonalPfAmount().stripTrailingZeros().toPlainString());
            // 公司社保
            resultItem.setCompanySocStr(resultItem.getSysCompanySocAmount().stripTrailingZeros().toPlainString() + "/" +
                    resultItem.getExcelCompanySocAmount().stripTrailingZeros().toPlainString());
            // 公司公积金
            resultItem.setCompanyPfStr(resultItem.getSysCompanyPfAmount().stripTrailingZeros().toPlainString() + "/" +
                    resultItem.getExcelCompanyPfAmount().stripTrailingZeros().toPlainString());
            // 服务费
            BigDecimal sysServiceCost = socCheckService.checkNull(resultItem.getSysServiceCost());
            BigDecimal excelServiceCost = socCheckService.checkNull(resultItem.getExcelServiceCost());
            resultItem.setServiceCostStr(sysServiceCost.stripTrailingZeros().toPlainString() + "/" +
                    excelServiceCost.stripTrailingZeros().toPlainString());
            // 补收滞纳金
            BigDecimal sysSocialSecurityFine = socCheckService.checkNull(resultItem.getSysSocialSecurityFine());
            BigDecimal excelSocialSecurityFine = socCheckService.checkNull(resultItem.getExcelSocialSecurityFine());
            resultItem.setSocialSecurityFineStr(sysSocialSecurityFine.stripTrailingZeros().toPlainString() + "/" +
                    excelSocialSecurityFine.stripTrailingZeros().toPlainString());
            // 补缴滞纳金
            BigDecimal sysAccumulationFundFine = socCheckService.checkNull(resultItem.getSysAccumulationFundFine());
            BigDecimal excelAccumulationFundFine = socCheckService.checkNull(resultItem.getExcelAccumulationFundFine());
            resultItem.setAccumulationFundFineStr(sysAccumulationFundFine.stripTrailingZeros().toString() + "/" +
                    excelAccumulationFundFine.stripTrailingZeros().toString());
            if (!ObjectUtils.isEmpty(resultItem.getPayCostType())) {
                resultItem.setPayCostTypeStr(SocPayCostType.find(resultItem.getPayCostType()).getDesc());
            }
            result.add(resultItem);
        }
        return result;
    }

    @Override
    public List<SocCheckItemVO> selectBySocCheckId(String socCheckId, TokenUser tokenUser) {
        Example example = new Example(SocCheckItemDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("socCheckId", socCheckId)
                .andEqualTo("siteId", tokenUser.getSiteId());
        example.orderBy("empId");
        List<SocCheckItemDO> socCheckItemList = socCheckItemDAO.selectByExample(example);
        return socCheckItemList.stream()
                .map(socCheckItemDO -> socCheckItemDO.to(SocCheckItemVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public List<SocCheckItemVO> additionalSocCheckItem(String socCheckId, Integer wrongsStatus, TokenUser tokenUser) {
        List<SocCheckItemVO> socCheckItemList = selectBySocCheckIdAndWrongsStatus(socCheckId, wrongsStatus, tokenUser);
        List<String> socProgIdList = socCheckItemList.stream()
                .filter(socCheckItemDO -> !StringUtils.isEmpty(socCheckItemDO.getSocProgId()))
                .map(SocCheckItemVO::getSocProgId)
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(socProgIdList)) {
            List<SocProgDO> socProgList = socProgService.selectByIdList(socProgIdList, tokenUser);
            Map<String, SocProgDO> socProgMap =
                    socProgList.stream().collect(Collectors.toMap(SocProgDO::getId, v -> v));
            for (SocCheckItemVO socCheckItemVO : socCheckItemList) {
                if (!StringUtils.isEmpty(socCheckItemVO.getSocProgId())) {
                    SocProgDO socProgDO = socProgMap.get(socCheckItemVO.getSocProgId());
                    socCheckItemVO.setSocProgCity(socProgDO.getSocCityName());
                    socCheckItemVO.setSocProgName(socProgDO.getProgName());
                }
            }
        }
        return socCheckItemList;
    }

    @Override
    public String exportPathBySocCheckId(SocCheckItemQuery socCheckItemQuery, TokenUser tokenUser) {
        SocCheckVO socCheckVO = socCheckService.selectById(socCheckItemQuery.getSocCheckId(), tokenUser.getSiteId());
        if (ObjectUtils.isEmpty(socCheckVO)) {
            throw new HrException("未找到此次校验结果信息");
        }
        String excelPath;
        // 要导出的数据
        List<SocCheckItemExportVO> socCheckItemExportVOList = selectExportList(socCheckItemQuery, tokenUser);
        // 导出excel
        excelPath = ExcelKit.exportExcel("socCheckItemCustom", "错误数据", SocCheckItemExportVO.class, socCheckItemExportVOList);
        return excelPath;
    }

    private List<SocCheckItemVO> selectBySocCheckIdAndWrongsStatus(String socCheckId, Integer wrongsStatus, TokenUser tokenUser) {
        Example example = new Example(SocCheckItemDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("socCheckId", socCheckId)
                .andEqualTo("siteId", tokenUser.getSiteId());
        if (!ObjectUtils.isEmpty(wrongsStatus)) {
            example.and().andEqualTo("wrongsStatus", wrongsStatus);
        }
        example.orderBy("empId");
        List<SocCheckItemDO> socCheckItemList = socCheckItemDAO.selectByExample(example);
        return socCheckItemList.stream()
                .map(socCheckItemDO -> socCheckItemDO.to(SocCheckItemVO.class))
                .collect(Collectors.toList());
    }

    /**
     * 根据查询参数，构建example
     *
     * @param socCheckItemQuery 查询参数
     * @param siteId            所属站点id
     * @return example
     */
    private Example buildExample(SocCheckItemQuery socCheckItemQuery, String siteId) {
        Example example = new Example(SocCheckItemDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        // 排序
        ExampleKit.setExampleOrder(example, socCheckItemQuery.getOrders());
        return example;
    }
}




